import { login, getUserInfo, getUserPerm } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}

  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      setToken(token)
      //保存时间戳
      localStorage.setItem('loginTime',Date.now())
    },

    // 删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 保存用户信息
    setUserInfo(state, data) {
      state.userInfo = data
    },
    getUserInfo(state) {
      state.userInfo={}
    }
    
  },
  actions: {
    async login(store, data) {
      const res = await login(data)

      store.commit('SET_TOKEN', res.data.jwt)
    },
    // 获取用户信息 
    async getUserInfo(store) {
      const res = await getUserInfo()
      console.log('获取到的用户信息', res)
      // 获取用户当前的权限
      const result = await getUserPerm()
      console.log('获取到的用户权限', result)
      store.commit('setUserInfo', { ...res.data, ...result.data })
    },
     // 退出登录
     logout(store) {
      store.commit('removeToken')
      store.commit('getUserInfo')
    }

  }
}
